package init

import (
	"day12_11_homework/config"
	"day12_11_homework/internal/models/dao"
	"fmt"
	"github.com/go-redis/redis/v8"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"sync"
)

var (
	err error
)

func init() {
	Init()
	MySQLInit()
	RedisInit()
}

func Init() {
	viper.SetConfigFile("C:\\Users\\DB\\goWork\\src\\day12_11_homework\\application.yaml")
	err = viper.ReadInConfig()
	if err != nil {
		fmt.Println("配置文件读取失败")
		return
	} else {
		fmt.Println("配置文件读取成功")
	}
	err = viper.Unmarshal(&config.Configs)
	if err != nil {
		fmt.Println("配置文件解析失败")
		return
	} else {
		fmt.Println("配置文件解析成功")
	}
}

func MySQLInit() {
	var once sync.Once
	appConfig := config.Configs.MySQLConfig
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local",
		appConfig.User, appConfig.Password, appConfig.Host, appConfig.Port, appConfig.Database)
	once.Do(func() {
		config.DB, err = gorm.Open(mysql.Open(dsn))
		if err != nil {
			fmt.Println("mysql连接失败")
			return
		} else {
			fmt.Println("mysql连接成功")
		}
	})
	err = config.DB.AutoMigrate(&dao.User{})
	if err != nil {
		fmt.Println("表迁移失败")
	} else {
		fmt.Println("表迁移成功")
	}
}

func RedisInit() {
	config.Rdb = redis.NewClient(&redis.Options{
		Addr:     config.Configs.RedisConfig.Host,
		Password: config.Configs.RedisConfig.Password,
		DB:       config.Configs.RedisConfig.DB,
	})
	err = config.Rdb.Ping(config.Ctx).Err()
	if err != nil {
		fmt.Println("redis连接失败")
		return
	} else {
		fmt.Println("redis连接成功")
	}
}
